<template>
  <div class="tp h-full flex flex-col">
    <Header />
    <Content class="flex-1 overflow-auto">
      <div class="cp">
        <div class="card">
          <div class="c-title"> 基础信息</div>

          <BasicForm @register="registerForm1" class="form" />
        </div>

        <div class="card">
          <div class="c-title">
            <span>员工账号信息</span
            ><span class="hint">该账号为员工登录店务系统的账号密码，请谨慎填写</span>
          </div>

          <BasicForm @register="registerForm2" class="form" />
        </div>

        <div class="card">
          <div class="c-title"> 其他信息</div>

          <BasicForm @register="registerForm3" class="form">
            <template #image="{ field }" @mousemove.stop="state.accept = 'image/png, image/jpeg'">
              <Attachment
                :accept="state.accept"
                list-type="picture-card"
                :multiple="false"
                :maxCount="1"
                :disabled="false"
                v-model:data-source="state.form[field]"
              />
            </template>
          </BasicForm>
        </div>
      </div>
    </Content>

    <Footer class="">
      <a-flex vertical align="center" justify="center" gap="middle" class="f-body">
        <a-button block type="primary" v-if="state.behavior === 'edit'" danger @click="onSave(1)"> 确认并保存</a-button>
        <a-button block type="primary" v-else danger @click="onSave(2)"> 确认并保存</a-button>
        <a-button block @click="router.back()">取消编辑</a-button>
        <!-- <a-button type="primary" @click="onSave(1)"
          >{{ state.behavior === 'edit' ? '保存' : '完成' }}
        </a-button> -->
      </a-flex>
    </Footer>
  </div>
</template>
<script setup>
  import { defineOptions, onMounted, reactive, ref } from 'vue';
  import { BasicForm, useForm } from '@/components/Form/index';

  import Attachment from '@/widget/attachment.vue';
  import { staffRole, staffStatus } from '@/api/ds';
  import Header from '@/widget/header.vue';
  import Content from '@/widget/content.vue';
  import Footer from '@/widget/footer.vue';

  import { useRoute, useRouter } from 'vue-router';
  import { POST, PUT } from '@/api/http';
  import dayjs from 'dayjs';
  import { getAttachment, initImgAttachment, jointPath } from '@/api/util';
  import { useMessage } from '@/hooks/web/useMessage';

  defineOptions({});

  const { createMessage } = useMessage();
  const route = useRoute(),
    router = useRouter();
  const { employeeCode = null } = route.query;
  const { behavior } = route.meta;

  const state = reactive({
    accept:'image/png, image/jpeg',
    behavior,
    form: { headImgUrl: [] },
  });

  const [registerForm1, form1] = useForm({
    labelWidth: 100,
    baseColProps: { span: 8, style: { paddingRight: '36px' } },

    schemas: [
      {
        label: '员工姓名',
        field: 'realName',
        required: true,
        component: 'Input',
      },

      {
        label: '手机号码',
        field: 'mobile',
        component: 'Input',
        rules: [
          { required: true },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' },
          {
            validator: (_, value) =>
              !!value && recordRef.value?.mobile !== value
                ? POST(
                    '/membership/checkEmployeeCodeAndMobile',
                    { mobile: value },
                    { errorMessageMode: 'none' },
                  )
                : Promise.resolve(),
          },
        ],
        componentProps: {
          onChange(e) {
            if (e?.target) {
              form2.setFieldsValue({ mobile: e?.target?.value });
            }
          },
        },
      },
      {
        label: '',
        field: '',
        required: false,
        component: 'Input',
        componentProps: {
          class: 'hidden',
        },
      },
      {
        label: '店铺角色',
        field: 'stationCode',
        required: true,
        component: 'RadioGroup',
        componentProps: {
          options: staffRole,
        },
      },

      {
        label: '在职状态',
        field: 'status',
        required: true,
        component: 'RadioGroup',
        componentProps: {
          options: staffStatus,
        },
      },

      {
        label: '是否可预约',
        field: 'storeBooking',
        required: true,
        component: 'Switch',
        componentProps: {
          checkedValue: '1',
          unCheckedValue: '0',
          // checkedChildren: '可预约',
          // unCheckedChildren: '不可预约',
        },
      },
    ],
    showActionButtonGroup: false,
  });

  const [registerForm2, form2] = useForm({
    labelWidth: 100,
    baseColProps: { span: 8, style: { paddingRight: '36px' } },

    schemas: [
      {
        label: '员工账号',
        field: 'mobile',
        required: false,
        component: 'Input',
        componentProps: {
          placeholder: '请输入手机号码作为员工账号',
          disabled: true,
        },
      },

      {
        label: '登录密码',
        field: 'passWord',
        component: 'InputPassword',
        componentProps: {
          // disabled: state.behavior === 'edit',
          placeholder:
            state.behavior === 'edit' ? '' : '请输入数字、字母、特殊字符组成的8-15位字符',
          maxlength: 15,
        },
        rules: [
          { required: state.behavior === 'add' },

          state.behavior === 'add' && {
            // pattern: /^(?=.*[A-Za-z])(?=.*\d)(?=.*[@#^_\-~+=$!%*?&])[A-Za-z\d@#^_\-~+=$!%*?&]{8,15}$/,
            pattern: /^(?=.*\d)(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{8,15}$/,
            message: '密码必须由数字、字母、特殊字符组成的8-15位字符',
          },
        ].filter((o) => o !== false),
      },
    ],
    showActionButtonGroup: false,
  });

  const [registerForm3, form3] = useForm({
    labelWidth: 100,
    baseColProps: { span: 8, style: { paddingRight: '36px' } },

    schemas: [
      {
        label: '身份证号',
        field: 'cardNum',
        component: 'Input',
        rules: [
          { required: false },
          {
            pattern:
              /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9xX]$/,
            message: '请输入正确的身份证号',
          },
        ],
      },

      {
        label: '员工生日',
        field: 'birthday',
        required: false,
        component: 'DatePicker',
        componentProps: {
          format: 'YYYY-MM-DD',
          valueFormat: 'YYYY-MM-DD',
          disabledDate: (value) => value.toDate().getTime() > new Date().getTime(),
        },
      },

      {
        label: '入职日期',
        field: 'entryDate',
        required: false,
        component: 'DatePicker',
        componentProps: {
          format: 'YYYY-MM-DD',
          valueFormat: 'YYYY-MM-DD',
        },
        colProps: {
          offset: 8,
          pull: 8,
        },
      },

      {
        label: '离职日期',
        field: 'leaveDate',
        component: 'DatePicker',
        componentProps: {
          format: 'YYYY-MM-DD',
          valueFormat: 'YYYY-MM-DD',
        },
        rules: [
          { required: false },
          {
            validator: () => {
              const { entryDate, leaveDate } = form3.getFieldsValue();

              return !!entryDate &&
                !!leaveDate &&
                dayjs(entryDate, 'YYY-MM-DD').toDate().getTime() >
                  dayjs(leaveDate, 'YYY-MM-DD').toDate().getTime()
                ? Promise.reject('入职日期不能大于离职日期')
                : Promise.resolve();
            },
          },
        ],
        colProps: {
          pull: 8,
        },
      },

      {
        label: '员工头像',
        field: 'headImgUrl',
        required: false,
        component: 'Upload',
        slot: 'image',
        customValidator: (rule, value, callback) => {
          if (!value) {
            callback(new Error('请选择员工头像'));
          } else {
            const allowedFormats = ['image/jpeg', 'image/png', 'image/gif']; // 允许的图片格式
            const isImage = allowedFormats.includes(value.type);
            if (!isImage) {
              callback(new Error('请上传正确的图片格式'));
            } else {
              callback();
            }
          }
        }
      },
    ],
    showActionButtonGroup: false,
  });

  const formList = [form1, form2, form3];
  const recordRef = ref({});

  onMounted(async () => {
    const initData = { status: 1, storeBooking: '1' };

    if (state.behavior === 'edit') {
      recordRef.value = (await POST('/membership/getEmployeeInfoBean', { employeeCode })) ?? {};
    }

    //初始化表单
    Object.assign(initData, recordRef.value);
    Object.assign(state.form, initImgAttachment(recordRef.value, ['headImgUrl']));

    formList.forEach((f) => {
      f.setFieldsValue(initData);
    });
  });

  async function onSave(type) {
    await Promise.all(formList.map((f) => f.validate()));
    const formData = formList.reduce((prev, f) => Object.assign(prev, f.getFieldsValue()), {});

    //附件
    const { headImgUrl } = state.form;
    formData.headImgUrl = getAttachment(headImgUrl)?.[0]?.url ?? null;

    //保存
    const data = { ...recordRef.value, ...formData };
    await (state.behavior === 'add'
      ? POST('/membership/addEmployeeInfoBean', data)
      : PUT('/membership/updateEmployeeInfoBean', data));
    createMessage.success('员工信息已保存');

    if (type === 2) {
      await router.replace(jointPath(route.path, { t: Math.random() }));
    } else {
      await router.back();
    }
  }
</script>

<style lang="less" scoped>
  .card {
    margin: 8px 0 24px;
    padding: 16px;
    background-color: #fff;

    .c-title {
      display: flex;
      flex-direction: row;
      align-items: center;
      column-gap: 8px;
      color: #091f3d;
      font-size: 14px;
      font-weight: 600;
    }

    .form {
      padding: 24px 12px 0 0;
    }

    .hint {
      color: #acb4bf;
      font-size: 10px;
      font-weight: 400;
    }
  }
</style>
